package com.tlb.springboot.starter.rocketmq.message;


import com.aliyun.openservices.shade.com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.shade.com.alibaba.rocketmq.common.message.Message;

/**
 * @author yuaneg 2018/8/30
 */
public class DefaultMessage extends Message {

    public DefaultMessage(String topic, Object body) {
        super(topic, toBytes(body));
    }

    public DefaultMessage(String topic, String tags, String keys, int flag, Object body, boolean waitStoreMsgOK) {
        super(topic, tags, keys, flag, toBytes(body), waitStoreMsgOK);
    }

    public DefaultMessage(String topic, String tags, Object body) {
        super(topic, tags, toBytes(body));
    }

    public DefaultMessage(String topic, String tags, String keys, Object body) {
        super(topic, tags, keys, toBytes(body));
    }


    public DefaultMessage(Object body) {
        super(null, toBytes(body));
    }


    private static byte[] toBytes(Object object) {
        if (null == object) {
            throw new RuntimeException("object can not be null");
        }
        if (object instanceof String) {
            return ((String) object).getBytes();
        }
        return JSONObject.toJSONString(object).getBytes();
    }

    public void setBody(Object body) {
        super.setBody(toBytes(body));
    }

    /**
     * 定时消息设置 eg: value = System.currentTimeMillis() + ????
     * 只有阿里云版本的rocketmq 支持此属性   开源版本不支持
     */
    public void setStartDeliverTime(long value) {
        super.putUserProperty(SystemPropKey.STARTDELIVERTIME, String.valueOf(value));
    }

    public long getStartDeliverTime() {
        String pro = super.getUserProperty(SystemPropKey.STARTDELIVERTIME);
        return pro != null ? Long.parseLong(pro) : 0L;
    }


    public static class SystemPropKey {
        public static final String TAG = "__TAG";
        public static final String KEY = "__KEY";
        public static final String MSGID = "__MSGID";
        public static final String SHARDINGKEY = "__SHARDINGKEY";
        public static final String RECONSUMETIMES = "__RECONSUMETIMES";
        public static final String BORNTIMESTAMP = "__BORNTIMESTAMP";
        public static final String BORNHOST = "__BORNHOST";
        public static final String STARTDELIVERTIME = "__STARTDELIVERTIME";

        public SystemPropKey() {
        }
    }

}
